package coder.user.service.impl;

import coder.common.BaseContext;
import coder.common.Result;
import coder.exception.BaseException;
import coder.user.entity.Address;
import coder.user.mapper.AddressMapper;
import coder.user.service.IAddressService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {
    @Override
    public void saveAddress(Address address) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, BaseContext.getCurrentId()).eq(Address::getIsDelete, 0);
        int addressCount = this.count(queryWrapper);
        if(addressCount == 5) {
            throw new BaseException("最多只能添加5个地址");
        }
        this.save(address);
    }

    /**
     * 根据用户ID查询地址列表
     *
     * 此方法使用LambdaQueryWrapper来构造查询条件， specifically targeting the current user's ID
     * It leverages the MyBatis-Plus framework's lambda query feature to safely and efficiently query the database
     *
     * @return A list of Address objects belonging to the current user If no addresses are found, returns an empty list
     */
    @Override
    public List<Address> queryAddress() {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, BaseContext.getCurrentId()).eq(Address::getIsDelete, 0);
        return this.list(queryWrapper);
    }
}
